import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import javax.swing.AbstractListModel;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;


public class SquareUI extends JFrame implements ActionListener {
	
	private MyListModel mlm;
	
	public SquareUI() {
		setSize(200, 300);
		setLocationRelativeTo(null);
		setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		try {
			add(new JScrollPane(new JList(mlm = new MyListModel("carres.dat"))));
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		JButton btnSum = new JButton("SUM");
		btnSum.addActionListener(this);
		
		Box bxBtn = Box.createHorizontalBox();
		bxBtn.add(btnSum);
		add(bxBtn);
		
		setVisible(true);
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		int i, ct=mlm.getSize(), acc=0;
		for (i=0; i<ct; i++)
			acc += mlm.getElementAt(i);
		JOptionPane.showMessageDialog(this, "Sum: "+acc);
	}

	class MyListModel extends AbstractListModel<Integer> {
		
		private RandomAccessFile src;
		private int size;
		
		public MyListModel(String filename) throws FileNotFoundException {
			src = new RandomAccessFile(filename, "r");
			try {
				size = (int)src.length()/4;
			} catch (IOException e) {
				size = 0;
			}
		}

		@Override
		public Integer getElementAt(int pos) {
			System.out.println("getElementAt("+pos+")"); 
			try {
				src.seek(pos*4);
				return src.readInt();
			} catch (IOException e) {
				return -1;
			}
		}

		@Override
		public int getSize() {
			System.out.println("getSize");
			return size;
		}
		
	}
	
	public static void main(String[] args) {
		new SquareUI();
	}

}
